package com.drojian.demo1.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.drojian.demo.R;
import com.drojian.demo1.pojo.Fruit;

import java.util.ArrayList;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {
    private final Context context;
    private  ArrayList<Fruit> datas;

    public MyRecyclerViewAdapter(Context context, ArrayList<Fruit> datas) {
        this.context = context;
        this.datas = datas;

    }

    /**
     * 相当于getView方法中的创建view和viewHolder
     * @param parent The ViewGroup into which the new View will be added after it is bound to
     *               an adapter position.
     * @param viewType The view type of the new View.
     *
     * @return
     */
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView=View.inflate(context, R.layout.item_recyclerview,null);
        return new MyViewHolder(itemView);
    }

    //数据和getView绑定
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        // 根据位置得到数据进行绑定
        Fruit fruit = datas.get(position);
        holder.imageId.setImageResource(fruit.getId());
        holder.imageName.setText(fruit.getName());
    }


    /**
     * 总条数
     * @return
     */
    @Override
    public int getItemCount() {
        return datas.size();
    }




    class MyViewHolder extends RecyclerView.ViewHolder{
        //实例化RecyclerView的item
        private ImageView imageId;
        private TextView imageName;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imageId = itemView.findViewById(R.id.imageId);
            imageName = itemView.findViewById(R.id.imageName);
            //设置点击事件
            imageId.setOnClickListener(v->Toast.makeText(context,"您点击了图片",Toast.LENGTH_SHORT).show());
            imageName.setOnClickListener(v->Toast.makeText(context,"您点击了"+datas.get(getLayoutPosition()).getName(),Toast.LENGTH_SHORT).show());
        }
    }

    public void addData(int position, Fruit fruit) {
        datas.add(fruit);
        notifyItemInserted(position);

    }
    public void aa(int position) {
        notifyItemInserted(position);

    }

    public void removeData(int position) {
        datas.remove(position);
        notifyItemRemoved(position);
    }
}
